#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy )
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout << "(" << _ix 
             << ", " << _iy
             << ")" << endl;
    }

    //将两个点加起来
    /* Point *addPoint(Point *pt) */
    shared_ptr<Point> addPoint(Point *pt)
    {
        _ix += pt->_ix;
        _iy += pt->_iy;

        /* return this; */
        /* return shared_ptr<Point>(this); */
        return shared_from_this();
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }

private:
    int _ix;
    int _iy;
};
void test()
{
    //使用了不同的智能指针托管了同一块堆空间
    int *pInt = new int(10);
    shared_ptr<int> sp(pInt);
    shared_ptr<int> sp2(pInt);//error
    /* shared_ptr<int> sp2(sp); //ok */
}

void test2()
{
    shared_ptr<int> sp(new int(1));
    shared_ptr<int> sp2(new int(2));

    sp.reset(sp2.get());
}

void test3()
{
    shared_ptr<Point> sp(new Point(1, 2));
    cout << "sp =  ";
    sp->print();

    cout << endl;
    shared_ptr<Point> sp2(new Point(3, 4));
    cout << "sp2 =  ";
    sp2->print();

    cout << endl;
    shared_ptr<Point> sp3(sp->addPoint(sp2.get()));
    cout << "sp3 =  ";
    sp3->print();
}

int main(int argc, char *argv[])
{
    test3();
    return 0;
}

